<!DOCTYPE html>
<html>
	<head>
		<meta charset="UTF-8">
		<title></title>
	</head>
	<style type="text/css">
		*{
			margin: 0;
			padding: 0;
		}
		body{
			position: relative;
		}
		
		#box{
			width: 401px;
			margin: 0 auto;
			height: 230px;
			border: 1px solid black;
		}
		
		
		#box1{
			width: 400px;
			height: 200px;
			border: 1px solid black;
		}
		#box1 p{
			width: 50px;
			height: 50px;
			/*border: 1px solid darkgoldenrod;*/
			background-color: lightskyblue;
		}
		#p2{
			width: 50px;
			height: 50px;
			border: 1px solid yellow;
			box-shadow: yellow 0 0 10px;
			
		}
		#box2{
			position: absolute;
			/*border: 1px solid black;*/
			bottom: 0;
		}
		#box2 button{
			width: 50px;
			height: 30px;
			border-radius: 30%;
			background-color: red;
			text-align: center;
			line-height: 30px;
		}
		
	</style>
	<script type="text/javascript">
		//产生指定范围的随机数
		function randomFun(min,max){
			return parseInt(Math.random()*(max - min)+ min)
		}
		window.onload = function(){
			//获取p1和p2标签
			var myP1 = document.querySelector('#p1')
			var myP2 = document.querySelector('#p2')
			
			
			//随机获取p1标签距离div上左的距离
			var left = randomFun(200,350);
			var top = randomFun(0,150);
			//把距离写进p1标签
			myP1.style.marginTop = top+'px';
			myP1.style.marginLeft = left +'px';
			//需要把myB2的背景图进行平移
			myP2.style.backgroundPosition = -1*left + 'px' + ' '+ -1*top + 'px';
			
			//计算p2到按钮的距离
			var p1Bottom = 150-top;
			myP2.style.marginBottom = 150-top+ 'px';
			
			//获取myP1的offsetleft值
			var myP1Left = myP1.offsetLeft;
			console.log(myP1Left)
					
			//获取btn所在的div
			var myBox2 = document.querySelector('#box2');
			//获取初始myBox2距离左边body的距离
			var myBox2Left = myBox2.offsetLeft
			
			//获取btn按钮
			var btn = document.querySelector('#box2 button'); 
			btn.onmousedown = function(ev){
				var e = ev || event;
				//获取鼠标在but的坐标
				var myX = e.offsetX;
				document.onmousemove=function(ev){
					var e = ev || event;
					//计算btn的移动的距离
					var btnX = e.pageX - myX;
					//判断btnX最小的距离不能小于myBox2Left
					if(btnX<myBox2Left){
						btnX = myBox2Left;
					}else if(btnX>myBox2Left+350){
						btnX = myBox2Left+350;
					}
					//把新坐标赋给btn
					myBox2.style.left = btnX+'px';
				}
				document.onmouseup = function(){
					document.onmousemove = null
					//获取移动之后按钮offsetLeft的值
					var newBtnLeft = myBox2.offsetLeft
					console.log(newBtnLeft)
					if(newBtnLeft > myP1Left - 3 && newBtnLeft <myP1Left+3){
						alert('验证成功')
					}else{
						myBox2.style.left= myBox2Left+'px';
					}
				}
			}
			
		}
	</script>
	<body>
		<div id="box">
			<div id="box1" style="background: url(124196.jpg);">
				<p id="p1"></p>
			</div>
			<div id="box2">
				<p id="p2" style="background: url(124196.jpg);"></p>
				<button>滑</button>
			</div>
		</div>
	</body>
</html>
